<?php

namespace Admin\Frontend\Controllers;

use Helpers\Tool;
use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\UserPower;
use Admin\Models\school\XhschoolGroup;

class SchoolgroupController extends ControllerBase
{

    private $groupEnum = [
        'iType' => [1 => '查看组', 2 => '管理组']
    ];

    /**
     * 学校组页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20170905
     */
    public function groupAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/schoolgroup/group.js');
        if (!UserPower::checkUserPower('School_Group')) {
            return $this->sendViewError('无查看权限');
        }
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'label' => '搜索：'];
        if (UserPower::checkUserPower('School_Group_Add')) {
            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'增加', 'icon'=>'fa-plus'];
        }
        if (UserPower::checkUserPower('School_Group_Del')) {
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash'];
        }
        if (UserPower::checkUserPower('School_Group_Contact')) {
            $listButtonArr[] = ['id'=>'bt_list_user', 'text'=>'关联用户', 'icon'=>'fa-pencil'];
            $listButtonArr[] = ['id'=>'bt_list_school', 'text'=>'关联学校', 'icon'=>'fa-pencil'];
        }
        return $this->view->setVars([
            'List' => Template::createList('List', 'School_Group', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ]);
    }

    /**
     * 获取学校分组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170905
     */
    public function getGroupAction()
    {
        $parameters = [
            'columns'   => 'iSGId,sGroupName,iType,mRemark,iUserNum,iSchoolNum,tCreateDate,iCreateUserId',
            'conditions'=> 'bDelete = 0'
        ];
        Main::runSearchVagueConditions($parameters['conditions'], ['sGroupName', 'mRemark']);
        $data = Main::runModelPage('\\Admin\\Models\\school\\XhschoolGroup', $parameters, $this->groupEnum);
        Main::runUserNameById($data['rows'], 'iCreateUserId', true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 创建学校分组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170905
     * modify by ck 20170906    添加组类型
     */
    public function createGroupAction()
    {
        if (!UserPower::checkUserPower('School_Group_Add')) {
            return $this->sendErrorResponse(400, '无添加权限');
        }
        $groupName = $this->request->getPost('groupName', 'string');
        $groupType = $this->request->getPost('groupType', 'int');
        $remark    = $this->request->getPost('remark', 'string');
        $isExist   = XhschoolGroup::findFirst([
            'conditions' => 'bDelete = 0 AND sGroupName = :groupName:',
            'bind'       => ['groupName' => $groupName]
        ]);
        if ($isExist) {
            return $this->sendErrorResponse(400, '组名不可重复');
        }
        $group = new XhschoolGroup();
        $group->sGroupName = $groupName;
        $group->iType      = $groupType;
        $group->mRemark    = $remark;
        if (!$group->save()) {
            return $this->sendErrorResponse(500, '创建失败');
        }
        return $this->sendSuccessResponse('创建成功');
    }

    /**
     * 删除学校分组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170905
     */
    public function delGroupAction()
    {
        if (!UserPower::checkUserPower('School_Group_Del')) {
            return $this->sendErrorResponse(400, '无删除权限');
        }
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少记录id');
        }
        $result = XhschoolGroup::deleteRecord('iSGId', $ids);
        if (!$result) {
            return $this->sendErrorResponse(500, '删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * 学校组关联用户页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20170905
     */
    public function groupUserAction()
    {
        if (!UserPower::checkUserPower('School_Group_Edit')) {
            return $this->sendViewError('无操作权限');
        }
        $this->view->setTemplateBefore('listlist');
        $groupId = $this->request->getQuery('groupId', 'int');
        if (!$groupId) {
            return $this->sendViewError('缺少学校组id');
        }
        Assets::easyUI('js/schoolgroup/groupUser.js');
        $outListSearchArr = [];
        $outListSearchArr[] = ['type' => 'select', 'id' => 'bt_list_out_company', 'data' => ['' => '全部', 1 => '员工'], 'style' => 'width: 70px;'];
        $outListSearchArr[] = ['type' => 'text', 'id' => 'list_out_vague', 'label' => ' 搜索：'];
        $outListSearchArr[] = ['type' => 'button', 'id' => 'bt_list_out_search', 'text' => '查找', 'icon' => 'fa-search'];
        return $this->view->setVars([
            'inList'    => Template::createList('list_in', 'School_GroupUser', [
                'title'         => '已关联用户',
            ]),
            'outList'   => Template::createList('list_out', 'School_GroupUser', [
                'title'         => '未关联用户',
                'searchToolbar' => Template::createSearchToolBar($outListSearchArr)
            ]),
        ]);
    }

    /**
     * 获取已关联/未关联学校组用户
     *
     * @param bool $getOut
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170905
     */
    public function getGroupUserAction($getOut = false)
    {
        $groupId = $this->request->getPost('groupId', 'int');
        $company = $this->request->getPost('company', 'int');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '缺少学校组id');
        }
        $group = XhschoolGroup::findFirst([
            'columns'    => 'mUserId',
            'conditions' => 'bDelete = 0 AND iSGId = :groupId:',
            'bind'       => ['groupId' => $groupId]
        ]);
        if (!$group) {
            return $this->sendErrorResponse(400, '找不到该记录');
        }
        $parameters = [
            'columns' => 'iUserId,sUserName,sLogonName,sSelfPhone',
            'conditions' => 'bDelete = 0 AND bDisable = 0'
        ];
        $userIds = trim($group->mUserId, ',');
        if ($getOut) {
            if ($userIds) {
                $parameters['conditions'] .= " AND iUserId NOT IN ({$userIds})";
            }
        }
        else {
            if ($userIds) {
                $parameters['conditions'] .= " AND iUserId IN ({$userIds})";
            }
            else {
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
        }

        //处理搜索条件
        if ($company) {
            $parameters['conditions'] .= " AND bCompany = 1";
        }
        Main::runSearchVagueConditions($parameters['conditions'], ['iUserId', 'sUserName', 'sLogonName', 'sSelfPhone']);
        $data = Main::runModelPage('\\Admin\\Models\\user\\XhsysUser', $parameters);
        return $this->sendJsonResponse($data);
    }

    /**
     * 添加/删除学校组用户
     *
     * @param bool $isDel
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170905
     */
    public function modifyGroupUserAction($isDel = false)
    {
        if (!UserPower::checkUserPower('School_Group_Edit')) {
            return $this->sendErrorResponse(400, '无操作权限');
        }
        $groupId = $this->request->getPost('groupId', 'int');
        $userIds = $this->request->getPost('userId', 'int');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '缺少学校组id');
        }
        if (!$userIds) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        $group = XhschoolGroup::findFirst([
            'conditions' => 'bDelete = 0 AND iSGId = :groupId:',
            'bind'       => ['groupId' => $groupId]
        ]);
        if (!$group) {
            return $this->sendErrorResponse(400, '找不到该记录');
        }
        if (!$isDel) {
            $group->mUserId = rtrim($group->mUserId, ',') . ',' . implode(',', $userIds) . ',';
        }
        else {
            foreach ($userIds as $userId) {
                $group->mUserId = str_replace(",{$userId},", ',', $group->mUserId);
            }
        }
        $group->iUserNum = substr_count($group->mUserId, ',') - 1;
        if (!$group->save()) {
            return $this->sendErrorResponse(500, '保存失败');
        }
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 学校组关联用户页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20170906
     */
    public function groupSchoolAction()
    {
        if (!UserPower::checkUserPower('School_Group_Edit')) {
            return $this->sendViewError('无操作权限');
        }
        $this->view->setTemplateBefore('listlist');
        $groupId = $this->request->getQuery('groupId', 'int');
        if (!$groupId) {
            return $this->sendViewError('缺少学校组id');
        }
        Assets::easyUI('js/schoolgroup/groupSchool.js');
        $outListSearchArr = [];
        $outListSearchArr[] = ['type' => 'text', 'id' => 'list_out_vague', 'label' => '搜索：'];
        $outListSearchArr[] = ['type' => 'button', 'id' => 'bt_list_out_search', 'text' => '查找', 'icon' => 'fa-search'];
        return $this->view->setVars([
            'inList'    => Template::createList('list_in', 'School_GroupSchool', [
                'title'         => '已关联学校',
            ]),
            'outList'   => Template::createList('list_out', 'School_GroupSchool', [
                'title'         => '未关联学校',
                'searchToolbar' => Template::createSearchToolBar($outListSearchArr)
            ]),
        ]);
    }

    /**
     * 获取已关联/未关联学校组学校
     *
     * @param bool $getOut
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170906
     */
    public function getGroupSchoolAction($getOut = false)
    {
        $groupId = $this->request->getPost('groupId', 'int');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '缺少学校组id');
        }
        $group = XhschoolGroup::findFirst([
            'columns'    => 'mSchoolId',
            'conditions' => 'bDelete = 0 AND iSGId = :groupId:',
            'bind'       => ['groupId' => $groupId]
        ]);
        if (!$group) {
            return $this->sendErrorResponse(400, '找不到该记录');
        }
        $parameters = [
            'columns'    => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete = 0 AND iStatus IN (1,2)'
        ];
        $schoolIds = trim($group->mSchoolId, ',');
        if ($getOut) {
            if ($schoolIds) {
                $parameters['conditions'] .= " AND iSchoolId NOT IN ({$schoolIds})";
            }
        }
        else {
            if ($schoolIds) {
                $parameters['conditions'] .= " AND iSchoolId IN ({$schoolIds})";
            }
            else {
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
        }
        Main::runSearchVagueConditions($parameters['conditions'], ['iSchoolId', 'sSchoolName']);
        $data = Main::runModelPage('\\Admin\\Models\\school\\XhschoolInfo', $parameters);
        return $this->sendJsonResponse($data);
    }

    /**
     * 添加/删除学校组学校
     *
     * @param bool $isDel
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170906
     */
    public function modifyGroupSchoolAction($isDel = false)
    {
        if (!UserPower::checkUserPower('School_Group_Edit')) {
            return $this->sendErrorResponse(400, '无操作权限');
        }
        $groupId    = $this->request->getPost('groupId', 'int');
        $schoolIds  = $this->request->getPost('schoolId', 'int');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '缺少学校组id');
        }
        if (!$schoolIds) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        $group = XhschoolGroup::findFirst([
            'conditions' => 'bDelete = 0 AND iSGId = :groupId:',
            'bind'       => ['groupId' => $groupId]
        ]);
        if (!$group) {
            return $this->sendErrorResponse(400, '找不到该记录');
        }
        if (!$isDel) {
            $group->mSchoolId = rtrim($group->mSchoolId, ',') . ',' . implode(',', $schoolIds) . ',';
        }
        else {
            foreach ($schoolIds as $schoolId) {
                $group->mSchoolId = str_replace(",{$schoolId},", ',', $group->mSchoolId);
            }
        }
        $group->iSchoolNum = substr_count($group->mSchoolId, ',') - 1;
        if (!$group->save()) {
            return $this->sendErrorResponse(500, '保存失败');
        }
        return $this->sendSuccessResponse('操作成功');
    }

}